//
//  JQFYPlayViewController.m
//  JQFY
//
//  Created by apple on 2017/8/9.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYPlayViewController.h"
#import "UIColor+Addition.h"
#import "JQFYMusicPlayer.h"
#import "CALayer+Animation.h"
#import "JQFYCustomNavigationView.h"
#import "MBProgressHUD+ZH.h"
#import "JQFYUMShare.h"

@interface JQFYPlayViewController ()

@property (nonatomic,weak) UISlider *progressSlider;              /// 进度条
@property (nonatomic,weak) UISlider *voiceSlider;                   /// 音量进度条
@property (nonatomic,weak) UIImageView *bgImageView;                /// 背景海报视图
@property (nonatomic,strong)  NSTimer *timer;                       /// 播放定时器
@property (nonatomic,weak) UILabel *durationLabel;                  /// 总时长Label
@property (nonatomic,weak) UILabel *currentTimeLabel;               /// 当前播放时长
@property (nonatomic,weak) UILabel *musicNameLabel;                 /// 音乐名字
@property (nonatomic,weak) UIButton *playButton;                    /// 播放按钮
@property (nonatomic,weak) UILabel *singerNameLabel;                /// 歌手
@property (nonatomic,weak) UIImageView *songPosterView;             /// 海报
@property (nonatomic,assign) NSUInteger playStatusIndex;            /// 播放模式索引
@property (nonatomic,weak) UIButton *circulationButton;             /// 循环模式按钮
@property (nonatomic,strong) JQFYCustomNavigationView *navgationView;// 自定义导航栏视图
@property (nonatomic,weak) UIImageView *bgPosterImageView;          /// 背景海报
@end

@implementation JQFYPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加子控件
    [self setupUI];
    // 自定义导航栏
    [self setupNav];
    
    [self setupNotification];  
    self.playStatusIndex = 0;
    self.timer = nil;

    NSInteger index = [[NSUserDefaults standardUserDefaults] integerForKey:NUMBERINDEX];
    switch (index) {
        case NSIntegerMax:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
            break;
        case 0:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"列表循环"] forState:UIControlStateNormal];
            break;
        case -888:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"随机播放(1)"] forState:UIControlStateNormal];
            break;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refreshUIWithSong:__Player__.playingSong];
    [self refreshUIWithStatus:__Player__.status];
    [self refreshUIWithCurrentTime:__Player__.currentTime totalTime:__Player__.totalTime];
    
}

static SEL extracted() {
    return @selector(playButtonPlayingAction:);
}

// 添加子控件
- (void)setupUI
{
    self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"WechatIMG13"].CGImage);

    UIBlurEffect *blue = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *eff = [[UIVisualEffectView alloc]initWithEffect:blue];
    [self.view addSubview:eff];
    eff.alpha = 0.9;
    [eff mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 歌曲海报
    UIImageView *songPosterView_ = [UIImageView new];
    [self.view addSubview:songPosterView_];
    [songPosterView_ mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64 *SCAL);
        make.width.height.mas_equalTo(DH_Screen_Width - 70 *SCAL);
        make.centerX.equalTo(self.view);
    }];
    
    self.songPosterView = songPosterView_;
    
    // 背景海报
    UIImageView *bgPosterImageView = [[UIImageView alloc] init];
    [self.view insertSubview:bgPosterImageView belowSubview:eff];
    [bgPosterImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    bgPosterImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.bgPosterImageView = bgPosterImageView;
    
    // 播放进度条
    UISlider *progressSlider = [UISlider new];
    [progressSlider setThumbImage:[UIImage imageNamed:@"Oval"] forState:UIControlStateNormal];
    [progressSlider setThumbImage:[UIImage imageNamed:@"Oval"] forState:UIControlStateHighlighted];
    [self.view addSubview:progressSlider];
    [progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(songPosterView_.mas_bottom).offset(25 *SCAL);
        make.height.mas_equalTo(20 *SCAL);
    }];
    self.progressSlider = progressSlider;
    [progressSlider addTarget:self action:@selector(settingPlayingCurrentTime:) forControlEvents:UIControlEventValueChanged];
    // 歌曲总时长
    UILabel *durationLabel = [self creatLabelWithFont:15 text:@"00:00"];
    [durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(progressSlider.mas_bottom).offset(5 *SCAL);
        make.right.equalTo(self.view).offset(-10 *SCAL);
    }];
    _durationLabel = durationLabel;
    // 歌曲当前播放时长
    UILabel *currentTimeLabel = [self creatLabelWithFont:15 text:@"00:00"];
    [currentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(durationLabel);
        make.left.equalTo(self.view).offset(10 *SCAL);
    }];
    self.currentTimeLabel = currentTimeLabel;
    
    // 播放按钮
    UIButton *playButton = [self creatButtonWithNormalImage:@"playing" andSelectImage:@"playing_Select" andHeightImage:nil];
    playButton.adjustsImageWhenHighlighted = NO;
    [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(durationLabel.mas_bottom).offset(30 *SCAL);
    }];
    _playButton = playButton;
    [playButton addTarget:self action:extracted() forControlEvents:UIControlEventTouchUpInside];
    
    // 上一曲
    UIButton *preButton = [self creatButtonWithNormalImage:@"Previous" andSelectImage:nil andHeightImage:@"Previous"];
    
    [preButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(playButton);;
        make.centerX.equalTo(self.view).multipliedBy(0.65);
    }];
    [preButton addTarget:self action:@selector(prev) forControlEvents:UIControlEventTouchUpInside];
    
    // 下一曲
    UIButton *nextButton = [self creatButtonWithNormalImage:@"Next" andSelectImage:nil andHeightImage:@"Next"];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).multipliedBy(1.35);
        make.centerY.equalTo(playButton);
    }];
    [nextButton addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放循环按钮
    UIButton *circulationButton = [self creatButtonWithNormalImage:@"Shuffle" andSelectImage:nil andHeightImage:nil];
    [circulationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(preButton);
        make.centerX.equalTo(self.view).multipliedBy(0.35);
    }];
    _circulationButton = circulationButton;
    [circulationButton addTarget:self action:@selector(circulationStatuChange) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *love = [self creatButtonWithNormalImage:@"未收藏" andSelectImage:@"已收藏" andHeightImage:nil];
    [self.view addSubview:love];
    [love mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).multipliedBy(1.65);
        make.centerY.equalTo(nextButton);
    }];
    [love addTarget:self action:@selector(loveSong:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *musicNameLabel = [self creatLabelWithFont:0 text:nil];
    musicNameLabel.userInteractionEnabled = YES;
    musicNameLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:35];
    musicNameLabel.textAlignment = NSTextAlignmentCenter;
    [musicNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(playButton.mas_bottom).offset(35 *SCAL);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(DH_Screen_Width * 0.7);
    }];
    _musicNameLabel = musicNameLabel;
    
    // 歌手
    UILabel *singerNameLabel = [self creatLabelWithFont:15 text:@"Now Playing"];
    singerNameLabel.userInteractionEnabled = YES;
    [singerNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(musicNameLabel.mas_bottom).offset(10 * SCAL);
        make.centerX.equalTo(self.view);
    }];
    _singerNameLabel = singerNameLabel;
    
    // 最小音量
    UIButton *minVoice = [self creatButtonWithNormalImage:@"SpeakerOff" andSelectImage:@"SpeakerOff" andHeightImage:nil];
    [self.view addSubview:minVoice];
    [minVoice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(currentTimeLabel);
        make.bottom.equalTo(self.view).offset(-25 *SCAL);
    }];
    [minVoice addTarget:self action:@selector(minVoice:) forControlEvents:UIControlEventTouchUpInside];
    
    // 最大音量
    UIButton *maxVoice = [self creatButtonWithNormalImage:@"SpeakerOn" andSelectImage:@"" andHeightImage:nil];
    [self.view addSubview:maxVoice];
    [maxVoice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10 *SCAL);
        make.centerY.equalTo(minVoice);
    }];
    [maxVoice addTarget:self action:@selector(maxVoice:) forControlEvents:UIControlEventTouchUpInside];
    
    // 音量滑竿
    UISlider *voice = [UISlider new];
    voice.value = 1;
    [self.view addSubview:voice];
    [voice setThumbImage:[UIImage imageNamed:@"Oval"] forState:UIControlStateNormal];
    [voice setThumbImage:[UIImage imageNamed:@"Oval"] forState:UIControlStateHighlighted];
    [voice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(minVoice);
        make.left.equalTo(minVoice.mas_right).offset(10 *SCAL);
        make.right.equalTo(maxVoice.mas_left).offset(-10 *SCAL);
    }];
    self.voiceSlider = voice;
    [voice addTarget:self action:@selector(changeVoice:) forControlEvents:UIControlEventValueChanged];
}

#pragma mark - 音量最小 -
- (void)minVoice:(UIButton *)button
{
    [__Player__ setVolume:0];
    self.voiceSlider.value = 0;
}
#pragma mark - 音量最大 -
- (void)maxVoice:(UIButton *)button
{
    [__Player__ setVolume:1];
    self.voiceSlider.value = 1;
}
#pragma mark - 设置通知 -
- (void)setupNotification {

    // 1. 安装播放状态发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerStatusDidChangedNotification:) name:JQFYMusicPlayerStatusDidChangedNotification object:__Player__];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerCurrentTimeDidChangedNotification:) name:JQFYMusicPlayerCurrentTimeDidChangedNotification object:__Player__];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:JQFYMusicPlayerPlayingSongDidChangedNotification object:__Player__];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dissMissAction) name:JQFYDissMissAction object:nil];
    
}

// 拖动进度条改变播放时间
- (void)settingPlayingCurrentTime:(UISlider *)slider
{
     [__Player__ setCurrentTime:slider.value * __Player__.totalTime];
}

/// 改变音量
- (void)changeVoice:(UISlider *)voice
{
    [__Player__ setVolume:voice.value];
    
}
#pragma mark - 通知监听方法 -
/// 音乐状态发生变化时的通知
- (void)musicPlayerStatusDidChangedNotification:(NSNotification *)notification {
    // 获取当前播放状态
    JQFYMusicPlayerStatus status = [notification.userInfo[kMusicPlayerStatus] integerValue];
    
    // 绑定播放状态和界面之间的关系
    [self refreshUIWithStatus:status];
    
}
/// 音乐时间变化时的通知
- (void)musicPlayerCurrentTimeDidChangedNotification:(NSNotification *)notification
{
    NSTimeInterval currentTime = [notification.userInfo[kCurrentTime] floatValue];
    NSTimeInterval totalTime = [notification.userInfo[kTotalTime] floatValue];
    
    [self refreshUIWithCurrentTime:currentTime totalTime:totalTime];
    
}
/// 换歌时的通知
- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    JQFYSong *playingSong = notification.userInfo[kMusicPlayerPlayingSong];
    [self refreshUIWithSong:playingSong];
}

/// 收藏歌曲
- (void)loveSong:(UIButton *)button
{
    button.selected = !button.selected;
}
#pragma mark - UI刷新 -
// 播放状态和界面之间的关系
- (void)refreshUIWithStatus:(JQFYMusicPlayerStatus)status {
    // 告诉播放按钮状态和播放器内部的状态之间的关系
    self.playButton.selected = status == JQFYMusicPlayerStatusPlaying;
}
// 通过播放的当前时间和总共时间刷新UI  sliderValue:(float)value
- (void)refreshUIWithCurrentTime:(float)currentTime totalTime:(float)totalTime {
    // 更新UI
    NSDateFormatter *dateFmt = [NSDateFormatter new];
    dateFmt.dateFormat = @"mm:ss";
    if (currentTime == 0.0) {
        return;
    }
    if ([self.durationLabel.text isEqualToString:@"00:00"]) {

        self.durationLabel.text = [dateFmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:totalTime]];
    }
    self.currentTimeLabel.text = [dateFmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:currentTime]];
    [self.progressSlider setValue:currentTime / totalTime animated:YES];
}

/// 刷新歌曲信息
- (void)refreshUIWithSong:(JQFYSong *)song
{
    [self.songPosterView sd_setImageWithURL:[NSURL URLWithString:song.music_cover_path] placeholderImage:[UIImage imageNamed:@"WechatIMG10 1"]];
    self.singerNameLabel.text = song.music_auth;
    self.musicNameLabel.text = song.music_name;
    [self.bgPosterImageView sd_setImageWithURL:[NSURL URLWithString:song.music_cover_path] placeholderImage:[UIImage imageNamed:@"WechatIMG10 1"]];
}

#pragma mark - 设置时长Label -
- (void)setDurationTimerWithTime:(NSTimeInterval)time
{
    if (time == 0) {
        return;
    }
    NSDateFormatter *dateFmt = [NSDateFormatter new];
    dateFmt.dateFormat = @"mm:ss";
    self.durationLabel.text = [dateFmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
}

#pragma mark - 开始播放歌曲 -
- (void)playSong
{
    if (__Player__.currentBtn) {
        __Player__.currentBtn.selected = YES;
    }
    [__Player__ play];
    
}

#pragma mark - 暂停播放 -
- (void)pausePlaying
{
    if (__Player__.currentBtn) {
        __Player__.currentBtn.selected = NO;
    }
    [__Player__ pause];
}

- (void)prev
{
    [__Player__ prev];
}

- (void)next
{
    [__Player__ next];
}
- (void)setupNav
{
    // 导航栏view
    self.navgationView = [JQFYCustomNavigationView new];
    [self.view addSubview:self.navgationView];
    [self.navgationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(20);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - 快速创建button -
- (UIButton *)creatButtonWithNormalImage:(NSString *)normalImageName andSelectImage:(NSString *)selectImageName andHeightImage:(NSString *)heightImageName
{
    UIButton *button = [UIButton new];
    [button setBackgroundImage:[UIImage imageNamed:normalImageName] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:heightImageName] forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:selectImageName] forState:UIControlStateSelected];
    [self.view addSubview:button];

    return button;
}

#pragma mark - 快速创建Label -
- (UILabel *)creatLabelWithFont:(float)font text:(NSString *)text
{
    UILabel *label = [UILabel new];
    label.font = [UIFont systemFontOfSize:font];
    label.text = text;
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
    return label;
}

#pragma mark - 播放按钮点击事件 -
- (void)playButtonPlayingAction:(UIButton *)button
{
    if (__Player__.status == JQFYMusicPlayerStatusPaused) {
        [self playSong];
    } else {
        [self pausePlaying];
    }
}

#pragma mark - 切换循环模式 -
- (void)circulationStatuChange
{
    return;
    self.playStatusIndex++;
    if (self.playStatusIndex > 2) {
        self.playStatusIndex = 0;
    }
    switch (self.playStatusIndex) {
        case 0:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
            __Player__.numIndex = NSIntegerMax;
            [MBProgressHUD showWithMessage:@"单曲模式"];
            [[NSUserDefaults standardUserDefaults] setInteger:NSIntegerMax forKey:NUMBERINDEX];
            break;
        case 1:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"列表循环"] forState:UIControlStateNormal];
            __Player__.numIndex = 0;
            [MBProgressHUD showWithMessage:@"循环模式"];
            [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:NUMBERINDEX];
            break;
        case 2:
            [self.circulationButton setBackgroundImage:[UIImage imageNamed:@"随机播放(1)"] forState:UIControlStateNormal];
            __Player__.numIndex = -888;
            [MBProgressHUD showWithMessage:@"随机模式"];
            [[NSUserDefaults standardUserDefaults] setInteger:-888 forKey:NUMBERINDEX];
            break;
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)dissMissAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
